/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cult.ticketing.action;

import cult.ticketing.bean.House;
import cult.ticketing.bean.Member;
import cult.ticketing.bean.Movie;
import cult.ticketing.bean.PurchaseRecord;
import cult.ticketing.bean.ScheduleItem;
import cult.ticketing.dao.HouseDAO;
import cult.ticketing.dao.MemberDAO;
import cult.ticketing.dao.MovieDAO;
import cult.ticketing.dao.PurchaseRecordDAO;
import cult.ticketing.dao.ScheduleItemDAO;
import cult.ticketing.processor.PurchaseProcessor;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author 51158282
 */
public class TicketingServlet extends HttpServlet {
    private final int AVAILABLE_SEAT = 0;
    private final int BOOKED_SEAT = 1;
    private final int NOT_AVAILABLE_SEAT = 2;
    private final int NOT_A_SEAT = -1;
    private final String MANAGER = "manager";
    private final String OFFICER = "officer";
    private final String CUSTOMER = "customer";
    private final String PURCHASE_BY_CREDIT_CARD = "purchaseByCreditCard";
    private final String PURCHASE_BY_LOYALTY_POINT = "purchaseByLoyaltyPoint";
    private final String OFFICER_PURCHASE = "officerPurchase";
    private final String SHOW_PURCHASE_RECORD = "showPurchaseRecord";
    private final String PREPARE_REFUND = "prepareRefundRequest";
    private final String SHOW_REFUND_STATUS = "showRefundStatus";
    private final String SHOW_PENDING_REFUND = "showPendingRefund";


    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jspPage = this.doIndexPage(request, response);

        this.dispatchJsp(jspPage, request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jspPage = "";

        if ("login".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doLoginPage(request, response);
        else if ("logout".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doLogoutPage(request, response);
        else if ("showAllMovies".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doShowAllMovies(request, response);
        else if ("searchMovie".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doSearchMovie(request, response);
        else if ("sortMovie".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doSortMovie(request, response);
        else if ("showScheduleItems".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doShowScheduleItems(request, response);
        else if ("showSeatingPlan".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doShowSeatingPlan(request, response);
        else if ("showCostSummary".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doPreparePurchase(request, response);
        else if (PURCHASE_BY_CREDIT_CARD.equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doPurchase(request, response, PURCHASE_BY_CREDIT_CARD);
        else if (PURCHASE_BY_LOYALTY_POINT.equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doPurchase(request, response, PURCHASE_BY_LOYALTY_POINT);
        else if (OFFICER_PURCHASE.equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doOfficerPurchase(request, response);
        else if ("signUp".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.signUp(request, response);
        else if ("doSignup".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doSignup(request, response);
        else if ("showLoyaltyPoint".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doShowLoyaltyPoint(request, response);
        else if (SHOW_PURCHASE_RECORD.equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doShowPurchaseRecord(request, response, SHOW_PURCHASE_RECORD);
        else if (PREPARE_REFUND.equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doShowPurchaseRecord(request, response, PREPARE_REFUND);
        else if (SHOW_REFUND_STATUS.equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doShowPurchaseRecord(request, response, SHOW_REFUND_STATUS);
        else if ("requestRefund".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doRequestRefund(request, response);
        else if ("addMovie".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.addMovie(request, response);
        else if ("updateMovie".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.updateMovie(request, response);
        else if ("deleteMovie".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.deleteMovie(request, response);
        else if ("addScheduleItem".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.addScheduleItem(request, response);
        else if ("updateScheduleItem".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.updateScheduleItem(request, response);
        else if ("deleteScheduleItem".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.deleteScheduleItem(request, response);
        else if ("addOfficer".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.addOfficer(request, response);
        else if ("deleteOfficer".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.deleteOfficer(request, response);
        else if ("doAddMovie".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doAddMovie(request, response);
        else if ("doUpdateMovie".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doUpdateMovie(request, response);
        else if ("doDoUpdateMovie".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doDoUpdateMovie(request, response);
        else if ("doDeleteMovie".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doDeleteMovie(request, response);
        else if ("doAddScheduleItem".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doAddScheduleItem(request, response);
        else if ("doUpdateScheduleItem".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doUpdateScheduleItem(request, response);
        else if ("doDeleteScheduleItem".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doDeleteScheduleItem(request, response);
        else if ("doAddOfficer".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doAddOfficer(request, response);
        else if ("doDeleteOfficer".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doDeleteOfficer(request, response);
        else if (SHOW_PENDING_REFUND.equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doShowPurchaseRecord(request, response, SHOW_PENDING_REFUND);
        else if ("authenticateRefund".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doAuthenticateRefund(request, response);
        else if ("prepareViewStatistics".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doPrepareViewStatistics(request, response);
        else if ("showStatistics".equalsIgnoreCase(request.getParameter("todo")))
            jspPage = this.doShowStatistics(request, response);
        else 
            jspPage = this.doIndexPage(request, response);

        this.dispatchJsp(jspPage, request, response);
    }

    private void dispatchJsp(String jspPage, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(jspPage).forward(request, response);
    }

    /**
     * Log in a member
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String doLoginPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        String email = request.getParameter("email");
        String pwd = request.getParameter("password");
        String msg = "";

        MemberDAO memberDAO = new MemberDAO();
        Member member = memberDAO.getMemberByEmail(email);

        if (member == null){
            //no such member
            msg = "This email address is not registered. Please sign up first.";
            session.setAttribute("loginResult", false);
        }
        else if (!member.getPwd().equals(pwd)) {
            // incorrect password   
            msg = "Your password is not correct. Please input again.";
            session.setAttribute("loginResult", false);
        }
        else {
            if (member.getLoginStatus() == true) {
                // already logged in elsewhere
                msg = "You have already logged in elsewhere. Please log off before you do another login.";
                session.setAttribute("loginResult", false);
            }
            else {
                session.setAttribute("loginResult", true);
                String role = member.getRole();
                int memberId = member.getId();
                session.setAttribute("memberId", memberId);
                session.setAttribute("email", email);
                session.setAttribute("role", role);
                memberDAO.updateLoginStatusById(memberId, true);
            }
        }
        session.setAttribute("msg", msg);

        return "jsp/index.jsp";
    }

    /**
     * Log out a member
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String doLogoutPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        int memberId =(Integer)session.getAttribute("memberId");
        MemberDAO memberDAO = new MemberDAO();
        memberDAO.updateLoginStatusById(memberId, false);
        session.removeAttribute("memberId");
        session.removeAttribute("email");
        session.removeAttribute("role");
        session.removeAttribute("loginResult");
        session.removeAttribute("msg");
        session.removeAttribute("loyaltyPoint");

        return "/jsp/index.jsp";
    }

    /**
     * Show all movies
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String doShowAllMovies(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean movieStatus = Boolean.parseBoolean(request.getParameter("movieStatus"));
        MovieDAO movieDAO = new MovieDAO();

        request.setAttribute("movies", movieDAO.getAllMovies(movieStatus));
        
        return "/jsp/now_showing.jsp";
    }

    /**
     * Search a movie
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String doSearchMovie (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String title = request.getParameter("title");
        MovieDAO movieDAO = new MovieDAO();

        request.setAttribute("movies", movieDAO.getMovieByTitle(title));

        return "/jsp/searchResult.jsp";
    }

    private String doSortMovie (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO sort logic

        //request.setAttribute("movies", movies);

        return "";
    }

    private String doShowScheduleItems (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int movieId = Integer.parseInt(request.getParameter("movieId"));
        ScheduleItemDAO scheduleItemDAO = new ScheduleItemDAO();
        
        request.setAttribute("scheduleItems", scheduleItemDAO.getScheduleItemByMovie(movieId));

        return "/jsp/schedule_item.jsp";
    }

    private String doShowSeatingPlan (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        if (session.getAttribute("role") != null && ((String)session.getAttribute("role")).equalsIgnoreCase(MANAGER))
            return "/jsp/index.jsp";

        int scheduleItemId = Integer.parseInt(request.getParameter("scheduleItemId"));

        ScheduleItemDAO scheduleItemDAO = new ScheduleItemDAO();
        ScheduleItem scheduleItem = scheduleItemDAO.getScheduleItemById(scheduleItemId);

        int houseId = scheduleItem.getHouseId();
        HouseDAO houseDAO = new HouseDAO();
        House house = houseDAO.getHouseById(houseId);
        int blockOneWidth = house.getBlockOneWidth();
        int blockTwoWidth = house.getBlockTwoWidth();
        int blockThreeWidth = house.getBlockThreeWidth();
        int houseWidth = blockOneWidth + blockTwoWidth + blockThreeWidth;
        int houseHeight = house.getHouseHeight();
        int blockCount = House.BLOCK_COUNT;
        int seatingPlanWidth = houseWidth + blockCount - 1;

        int[][] seatingPlan = new int[houseHeight][seatingPlanWidth];
        int[][] seatAvailability = new int [houseHeight][seatingPlanWidth];

        for (int i=0; i<houseHeight; i++) {
            int seatIndex = 1;
            for (int j=0; j<seatingPlanWidth; j++) {
                if ((j == blockOneWidth) || (j == blockOneWidth + blockTwoWidth + 1)){
                    seatingPlan[i][j] = NOT_A_SEAT;
                    seatAvailability[i][j] = NOT_A_SEAT;
                }
                else {
                    seatingPlan[i][j] = seatIndex;
                    seatIndex ++;
                    seatAvailability[i][j] = AVAILABLE_SEAT;
                }
            }
        }

        String bookedSeat = scheduleItem.getBookedSeat();
        String naSeat = scheduleItem.getNaSeat();

        String[] bookedSeatArr = bookedSeat.split(";");
        String[] naSeatArr = naSeat.split(";");

        for (int i=0; i<bookedSeatArr.length; i++){
            String[] xy = bookedSeatArr[i].split(",");
            int x = Integer.parseInt(xy[0]);
            int y = Integer.parseInt(xy[1]);
            seatAvailability[x][y] = BOOKED_SEAT;
        }

        for (int i=0; i<naSeatArr.length; i++){
            String[] xy = naSeatArr[i].split(",");
            int x = Integer.parseInt(xy[0]);
            int y = Integer.parseInt(xy[1]);
            seatAvailability[x][y] = NOT_AVAILABLE_SEAT;
        }

        session.setAttribute("scheduleItemId", scheduleItemId);
        
        request.setAttribute("seatingPlan", seatingPlan);
        request.setAttribute("seatAvailability", seatAvailability);
        request.setAttribute("houseHeight", houseHeight);
        request.setAttribute("seatingPlanWidth", seatingPlanWidth);

        return "/jsp/seating_plan.jsp";
    }

    private String doPreparePurchase (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        String seatIndex = request.getParameter("purchasedSeatIndex");
        int scheduleItemId = (Integer)session.getAttribute("scheduleItemId");

        PurchaseProcessor purchaseProcessor = new PurchaseProcessor(scheduleItemId);
        int totalCost = purchaseProcessor.calculatePurchase(seatIndex);
        session.setAttribute("totalCost", totalCost);
        session.setAttribute("seatIndex", seatIndex);   

        String role = (String)session.getAttribute("role");

        if (role != null && role.equalsIgnoreCase(CUSTOMER)) {
            int memberId = (Integer)session.getAttribute("memberId");
            MemberDAO memberDAO = new MemberDAO();
            int loyaltyPoint = memberDAO.getLoyaltyPointById(memberId);
            session.setAttribute("loyaltyPoint", loyaltyPoint);

            if (loyaltyPoint >= totalCost)
                request.setAttribute("isEnoughLoyaltyPoint", true);
            else
                request.setAttribute("isEnoughLoyaltyPoint", false);
        }

        return "/jsp/cost_summary.jsp";
    }

    private HttpSession removeSessionAttribute(HttpSession session){
        session.removeAttribute("scheduleItemId");
        session.removeAttribute("seatIndex");
        session.removeAttribute("totalCost");
        session.removeAttribute("isEnoughLoyaltyPoint");

        return session;
    }

    private String doPurchase (HttpServletRequest request, HttpServletResponse response, String purchaseMethod) throws ServletException, IOException {
        boolean isSuccessful = false;
        HttpSession session = request.getSession(true);
        int totalCost = (Integer)session.getAttribute("totalCost");
        int loyaltyPoint = -1;
        String seatIndex = session.getAttribute("seatIndex").toString();
        int scheduleItemId = (Integer)session.getAttribute("scheduleItemId");
        int memberId = -1;
        String email = "";
        final int NO_REFUND_REQUEST=-1;
	final int NOT_ALLOW_REFUND_REQUEST = -2;
        int refundStatus = NOT_ALLOW_REFUND_REQUEST;
        
        if (session.getAttribute("memberId") != null) {
            memberId = (Integer)session.getAttribute("memberId");
            email = (String)session.getAttribute("email");
            loyaltyPoint = (Integer)session.getAttribute("loyaltyPoint");
            refundStatus = NO_REFUND_REQUEST;
        }else {
            email = request.getParameter("email");
        }

        PurchaseProcessor purchaseProcessor = new PurchaseProcessor(memberId, scheduleItemId, email, seatIndex, totalCost, loyaltyPoint);

        if (purchaseMethod.equalsIgnoreCase(PURCHASE_BY_CREDIT_CARD))
            isSuccessful = purchaseProcessor.purchaseTicket(refundStatus);
        else
            isSuccessful = purchaseProcessor.purchaseTicketByLoyaltyPoint();

        removeSessionAttribute(session);

        ScheduleItemDAO scheduleItemDAO = new ScheduleItemDAO();
        ScheduleItem scheduleItem = scheduleItemDAO.getScheduleItemById(scheduleItemId);
        int movieId = scheduleItem.getMovieId();
        MovieDAO movieDAO = new MovieDAO();
        Movie movie = movieDAO.getMovieById(movieId);
        String movieTitle = movie.getTitle();
        String showTime = scheduleItem.getShowTime();

        request.setAttribute("movieTitle", movieTitle);
        request.setAttribute("showTime", showTime);
        request.setAttribute("seatIndex", seatIndex);
        request.setAttribute("purchaseResult", isSuccessful);

        return "/jsp/purchase_result.jsp";
    }

    private String doOfficerPurchase (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final int NOT_ALLOW_REFUND_REQUEST = -2;
        boolean isSuccessful = false;
        HttpSession session = request.getSession(true);
        int totalCost = (Integer)session.getAttribute("totalCost");
        int loyaltyPoint = -1;
        String seatIndex = session.getAttribute("seatIndex").toString();
        int scheduleItemId = (Integer)session.getAttribute("scheduleItemId");
        int memberId = -1;
        String memberEmail = "";
        String test = request.getParameter("memberEmail");

        if (!request.getParameter("memberEmail").equals("")) {
            memberEmail = request.getParameter("memberEmail");
            MemberDAO memberDAO = new MemberDAO();
            Member member = memberDAO.getMemberByEmail(memberEmail);
            memberId = member.getId();
            loyaltyPoint = member.getLoyaltyPoint();
        }

        PurchaseProcessor purchaseProcessor = new PurchaseProcessor(memberId, scheduleItemId, memberEmail, seatIndex, totalCost, loyaltyPoint);

        isSuccessful = purchaseProcessor.purchaseTicket(NOT_ALLOW_REFUND_REQUEST);

        ScheduleItemDAO scheduleItemDAO = new ScheduleItemDAO();
        ScheduleItem scheduleItem = scheduleItemDAO.getScheduleItemById(scheduleItemId);
        int movieId = scheduleItem.getMovieId();
        MovieDAO movieDAO = new MovieDAO();
        Movie movie = movieDAO.getMovieById(movieId);
        String movieTitle = movie.getTitle();
        String showTime = scheduleItem.getShowTime();

        request.setAttribute("movieTitle", movieTitle);
        request.setAttribute("showTime", showTime);
        request.setAttribute("seatIndex", seatIndex);
        request.setAttribute("purchaseResult", isSuccessful);


         return "/jsp/purchase_result.jsp";
    }

    private String doIndexPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*TODO Homepage
        GuestDAO guestDAO = new GuestDAO();
        request.setAttribute("guests", guestDAO.getGuests());
         */
        
        return "/jsp/index.jsp";
    }

    private String signUp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /*MemberDAO memberDAO = new MemberDAO();
        request.setAttribute("movie", MemberDAO.addNewMember(title));*/
        return "jsp/signup.jsp";
    }

    private String doSignup(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession(true);
        MemberDAO memberDAO = new MemberDAO();
        String email = request.getParameter("emailaddress");
        String pwd = request.getParameter("pwd");
        request.setAttribute("email", email);
        request.setAttribute("pwd", pwd);


        memberDAO.addNewMember(email,pwd,"costomer");
        return "jsp/index.jsp";
    }

    private String doShowLoyaltyPoint (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        int memberId = (Integer)session.getAttribute("memberId");
        MemberDAO memberDAO = new MemberDAO();
        int loyaltyPoint = memberDAO.getLoyaltyPointById(memberId);

        request.setAttribute("loyaltyPoint", loyaltyPoint);
        request.setAttribute("showOption", "showLoyaltyPoint");

        return "/jsp/profile.jsp";
    }

    private String doShowPurchaseRecord (HttpServletRequest request, HttpServletResponse response, String option) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        int memberId = (Integer)session.getAttribute("memberId");
        PurchaseRecordDAO purchaseRecordDAO = new PurchaseRecordDAO();
        ArrayList<ScheduleItem> scheduleItems = new ArrayList<ScheduleItem>();
        ArrayList<Movie> movies = new ArrayList<Movie>();
        ArrayList<PurchaseRecord> purchaseRecords = new ArrayList<PurchaseRecord>();
        String jspPage = "";

        if (option.equalsIgnoreCase(SHOW_PURCHASE_RECORD)) {
            purchaseRecords = purchaseRecordDAO.getPurchaseRecordByMemberId(memberId);
            request.setAttribute("showOption", SHOW_PURCHASE_RECORD);
            jspPage = "/jsp/profile.jsp";
        }
        else if (option.equalsIgnoreCase(SHOW_REFUND_STATUS)) {
            purchaseRecords = purchaseRecordDAO.getPurchaseRecordByMemberIdAndRefundStatus(memberId, "customerQuery");
            request.setAttribute("showOption", SHOW_REFUND_STATUS);
            jspPage = "/jsp/profile.jsp";
        }
         else if (option.equalsIgnoreCase(SHOW_PENDING_REFUND)) {
            purchaseRecords = purchaseRecordDAO.getPurchaseRecordByMemberIdAndRefundStatus(memberId, "managerQuery");
            request.setAttribute("showOption", SHOW_PENDING_REFUND);
            jspPage = "/jsp/management.jsp";
         }
        else {
            purchaseRecords= purchaseRecordDAO.getPurchaseRecordForRefundRequest(memberId);
            request.setAttribute("showOption", PREPARE_REFUND);
            jspPage = "/jsp/profile.jsp";
        }

        Iterator<PurchaseRecord> it = purchaseRecords.iterator();

        while (it.hasNext() != false) {
            int scheduleItemId = ((PurchaseRecord)it.next()).getScheduleItemId();
            ScheduleItemDAO scheduleItemDAO = new ScheduleItemDAO ();
            ScheduleItem scheduleItem = scheduleItemDAO.getScheduleItemById(scheduleItemId);
            scheduleItems.add(scheduleItem);

            int movieId = scheduleItem.getMovieId();
            MovieDAO movieDAO = new MovieDAO();
            Movie movie = movieDAO.getMovieById(movieId);
            movies.add(movie);
        }

        request.setAttribute("purchaseRecords", purchaseRecords);
        request.setAttribute("scheduleItems", scheduleItems);
        request.setAttribute("movies", movies);

        return jspPage;
        
    }

    private String doRequestRefund (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int purchaseRecordId = Integer.parseInt(request.getParameter("purchaseRecordId"));
        final int PENDING_REFUND = 0;

        PurchaseRecordDAO purcahseRecordDAO = new PurchaseRecordDAO ();
        PurchaseRecord purchaseRecord = purcahseRecordDAO.getPurchaseRecordById(purchaseRecordId);
        String seatIndex = purchaseRecord.getSeatIndex();
        int scheduleItemId = purchaseRecord.getScheduleItemId();
        ScheduleItemDAO scheduleItemDAO = new ScheduleItemDAO();
        boolean isSuccessful = purcahseRecordDAO.updateRefundStatusById(purchaseRecordId, PENDING_REFUND) && scheduleItemDAO.releaseBookedSeat(scheduleItemId, seatIndex);

        request.setAttribute("showOption", "showRefundRequestResult");
        request.setAttribute("isSuccessful", isSuccessful);

        return "/jsp/profile.jsp";
    }


    //Manager functions

    private String addMovie (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        return "/jsp/addMovie.jsp";
    }
    private String updateMovie (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        return "/jsp/updateMovie.jsp";
    }
    private String deleteMovie (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        MovieDAO movieDAO = new MovieDAO();

        request.setAttribute("movies", movieDAO.getAllMovies(false));
        request.setAttribute("movies", movieDAO.getAllMovies(true));

        return "/jsp/deleteMovie.jsp";
    }
    private String addScheduleItem (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        return "/jsp/addScheduleItem.jsp";
    }
    private String updateScheduleItem (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        return "/jsp/updateScheduleItem.jsp";
    }
    private String deleteScheduleItem (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        return "/jsp/deleteScheduleItem.jsp";
    }
    private String addOfficer (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        return "/jsp/addOfficer.jsp";
    }
    private String deleteOfficer (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession(true);
        MemberDAO memberDAO = new MemberDAO();
        request.setAttribute("members", memberDAO.getMemberByRole("officer"));


        return "/jsp/deleteOfficer.jsp";
    }



    private String doAddMovie (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        MovieDAO movieDAO = new MovieDAO();
        String name = request.getParameter("name");
        String date = request.getParameter("date");
        String director = request.getParameter("director");
        String actor = request.getParameter("actor");
        String introduction = request.getParameter("introduction");
        boolean status = Boolean.parseBoolean(request.getParameter("status"));
        String url = request.getParameter("url");

        request.setAttribute("name", name);
        request.setAttribute("date", date);
        request.setAttribute("director", director);
        request.setAttribute("actor", actor);
        request.setAttribute("introduction", introduction);
        request.setAttribute("status", status);
        request.setAttribute("url", url);



        movieDAO.addNewMovie(name,date,director,actor,introduction,status,url);

        return "/jsp/management.jsp";
    }
    private String doUpdateMovie (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);


        return "/jsp/doUpdateMovie.jsp";
    }
     private String doDoUpdateMovie (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        MovieDAO movieDAO = new MovieDAO();
        int movieId = Integer.parseInt(request.getParameter("movieId"));
        String name = request.getParameter("name");
        String date = request.getParameter("date");
        String director = request.getParameter("director");
        String actor = request.getParameter("actor");
        String introduction = request.getParameter("introduction");
        boolean status = Boolean.parseBoolean(request.getParameter("status"));
        String url = request.getParameter("url");

        request.setAttribute("name", name);
        request.setAttribute("date", date);
        request.setAttribute("director", director);
        request.setAttribute("actor", actor);
        request.setAttribute("introduction", introduction);
        request.setAttribute("status", status);
        request.setAttribute("url", url);
        
        Movie movie = movieDAO.updateMovieById(name,date,director,actor,introduction,status,url,movieId);
        
        return "/jsp/management.jsp";
    }
    private String doDeleteMovie (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);

        return "/jsp/management.jsp";
    }
    private String doAddScheduleItem (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        ScheduleItemDAO scheduleItemDAO = new ScheduleItemDAO();

        int movieID = Integer.parseInt(request.getParameter("movieID"));
        int houseID = Integer.parseInt(request.getParameter("houseID"));
        int price = Integer.parseInt(request.getParameter("price"));
        String showTime = request.getParameter("showTime");
        String bookedSeat = request.getParameter("bookedSeat");
        String naSeat = request.getParameter("naSeat");

        request.setAttribute("movieID", movieID);
        request.setAttribute("houseID", houseID);
        request.setAttribute("price", price);
        request.setAttribute("showTime", showTime);
        request.setAttribute("bookedSeat", bookedSeat);
        request.setAttribute("naSeat", naSeat);


        scheduleItemDAO.addNewScheduleItem(movieID,houseID,price,showTime,bookedSeat,naSeat);

        return "/jsp/management.jsp";
    }
    private String doUpdateScheduleItem (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);

        return "/jsp/management.jsp";
    }
    private String doDeleteScheduleItem (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);

        return "/jsp/management.jsp";
    }
    private String doAddOfficer (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        MemberDAO memberDAO = new MemberDAO();
        String email = request.getParameter("email");
        String pwd = request.getParameter("pwd");
        request.setAttribute("email", email);
        request.setAttribute("pwd", pwd);


        memberDAO.addNewMember(email,pwd,"officer");

        return "/jsp/management.jsp";
    }
    private String doDeleteOfficer (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);

        return "/jsp/management.jsp";
    }

    private String doAuthenticateRefund (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int purchaseRecordId = Integer.parseInt(request.getParameter("purchaseRecordId"));
        String decision = request.getParameter("decision");
        int refundDecision = 2; //Reject

        if (decision.equalsIgnoreCase("authenticate"))
            refundDecision = 1;

        PurchaseRecordDAO purcahseRecordDAO = new PurchaseRecordDAO ();
        boolean isSuccessful = purcahseRecordDAO.updateRefundStatusById(purchaseRecordId, refundDecision);

        request.setAttribute("showOption", "showRefundAuthenticatinResult");
        request.setAttribute("isSuccessful", isSuccessful);

        return "/jsp/management.jsp";
    }

    private String doPrepareViewStatistics(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean movieStatus = Boolean.parseBoolean(request.getParameter("movieStatus"));
        MovieDAO movieDAO = new MovieDAO();

        request.setAttribute("movies", movieDAO.getAllMovies());
        request.setAttribute("showOption", "prepareViewStatistics");
        
        return "/jsp/management.jsp";
    }

    private String doShowStatistics(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int movieId = Integer.parseInt(request.getParameter("movieId"));
        ArrayList<ScheduleItem> scheduleItems = new ArrayList<ScheduleItem>();
        ScheduleItemDAO scheduleItemDAO = new ScheduleItemDAO();
        scheduleItems = scheduleItemDAO.getScheduleItemByMovie(movieId);      
        MovieDAO movieDAO = new MovieDAO();
        Movie movie = movieDAO.getMovieById(movieId);
        int[] validSeatNum = new int[scheduleItems.size()];
        int[] bookedSeatNum = new int[scheduleItems.size()];
        int count = 0;

        Iterator<ScheduleItem> it = scheduleItems.iterator();

        while (it.hasNext() != false) {
            ScheduleItem scheduleItem = it.next();
            int scheduleItemId = scheduleItem.getId();
            int houseId = scheduleItem.getHouseId();

            HouseDAO houseDAO = new HouseDAO();
            House house = houseDAO.getHouseById(houseId);
            int houseCapacity = house.getCapacity();
            int naSeatNum = scheduleItem.getNaSeat().split(";").length;

            int validSeat = houseCapacity - naSeatNum;
            int bookedSeat = scheduleItem.getBookedSeat().split(";").length;

            validSeatNum[count] = validSeat;
            bookedSeatNum[count] = bookedSeat;
            count ++;

        }
        
        request.setAttribute("scheduleItems", scheduleItems);
        request.setAttribute("movie", movie);
        request.setAttribute("validSeatNum", validSeatNum);
        request.setAttribute("bookedSeatNum", bookedSeatNum);
        request.setAttribute("showOption", "showStatistics");

        return "/jsp/management.jsp";
    }
 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
